package com.hdlang.assists.ad.dao.service

import android.app.Service
import android.content.Intent
import android.os.IBinder
import com.hdlang.assists.ad.dao.step.JRNewsStep
import com.hdlang.assists.ad.utils.Constants
import com.ven.assists.stepper.StepListener
import com.ven.assists.stepper.StepManager
import java.util.concurrent.Executors
import java.util.concurrent.Future
import java.util.concurrent.ScheduledExecutorService
import java.util.concurrent.TimeUnit

class TaskService : Service(), Runnable, StepListener {

    companion object {
        val pool: ScheduledExecutorService = Executors.newScheduledThreadPool(3)
        var beforeRequestDate: Long = 0L
        val lock = Object()
    }

    private var future: Future<*>? = null

    override fun onCreate() {
        super.onCreate()
        setTimer()
        StepManager.stepListeners = this
        StepManager.execute(JRNewsStep::class.java, 1, begin = true)
    }

    override fun onBind(intent: Intent?): IBinder? {
        return null
    }

    private fun setTimer() {
        if ((future != null) && (future?.isDone != true || future?.isCancelled != true)) {
            future?.cancel(true)
        }
        var delay = 0L
        if (beforeRequestDate > 0) {
            val waitTime = System.currentTimeMillis() - beforeRequestDate
            delay = Constants.HEART_INTERVAL - waitTime
        }
        if (delay <= 0) {
            delay = Constants.HEART_INTERVAL
            runTask()
        }
        future = pool.schedule(this, delay, TimeUnit.MILLISECONDS)
    }

    override fun run() {
        synchronized(lock) {
            setTimer()
        }
    }

    private fun runTask() {
        if (StepManager.isStop) {
//            StepManager.execute(JRNewsStep::class.java, 1, begin = true)
        }
    }

}